package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/10/13 9:54
 * @Version V1.0
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public User findUserByUsername(String username) {
        User user = userDao.findUserByUsername(username);
        return user;
    }

    @Override
    public void add(Integer[] ids, User user) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userDao.add(user);
        addUserAndRole(ids,user.getId());

    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        // 1：获取检查组的基本信息，执行更新
        userDao.edit(user);
        // 2：使用检查组的id，删除中间表的数据
        userDao.deleteUserAndRoleByRoleIds(user.getId());
        // 3：重新遍历checkitemIds的数组，获取检查项的id，同时和检查组的id，向检查项和检查组的中间表插入多行数据
        addUserAndRole(roleIds,user.getId());
    }



    @Override
    public void delete(Integer id) {
       //先删除中间关系表的数据
        userDao.deleteUserAndRoleByRoleIds(id);
        // 删除检查项
        userDao.deleteById(id);
    }

    private void addUserAndRole(Integer[] ids, Integer user_id) {
        for(Integer role_id:ids){
            Map<String,Integer> map=new HashMap<>();
            map.put("user_id",user_id);
            map.put("role_id",role_id);
            userDao.addUserAndRole(map);
        }
    }
}
